const Follower = require('../models/follower');
const Notification = require('../models/notification');
const User = require('../models/user');

const followerController = {
    async follow(req, res, next) {
        try {
            const user = await User.findById(req.params.following_id);
            if (!user) {
                return res.status(404).json({ error: 'User not found' });
            }

            if (req.user.user_id === req.params.following_id) {
                return res.status(400).json({ error: 'Cannot follow yourself' });
            }

            const exists = await Follower.exists(req.user.user_id, req.params.following_id);
            if (exists) {
                return res.status(400).json({ error: 'Already following' });
            }

            await Follower.create({
                follower_id: req.user.user_id,
                following_id: req.params.following_id
            });

            await Notification.create({
                user_id: req.params.following_id,
                type: 'follow',
                related_user_id: req.user.user_id,
                content: `${req.user.user_id} followed you`
            });

            res.json({ message: 'Followed successfully' });
        } catch (error) {
            next(error);
        }
    },

    async unfollow(req, res, next) {
        try {
            const exists = await Follower.exists(req.user.user_id, req.params.following_id);
            if (!exists) {
                return res.status(400).json({ error: 'Not following' });
            }

            await Follower.delete(req.user.user_id, req.params.following_id);
            res.json({ message: 'Unfollowed successfully' });
        } catch (error) {
            next(error);
        }
    }
};

module.exports = followerController;